
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next'; // 引入 useTranslation
import './Products.css';
import { API_URL_TEMPLATE, YEARS } from '../config.js';

const NO_DATA_MESSAGE = '暂时无数据';

// 从翻译文件中获取时间周期和 Best of 文案
const useTimePeriodTranslations = () => {
  const { t } = useTranslation();
  const timePeriods = t('products.timePeriods', { returnObjects: true });
  const bestOf = t('products.bestOf');
  return { timePeriods, bestOf };
};

// 动态生成 NAV_MODES
const generateNavModes = (timePeriods) => {
  return [
    { key: 'day', label: timePeriods[0], text: timePeriods[0] },
    { key: 'week', label: timePeriods[1], text: timePeriods[1] },
    { key: 'month', label: timePeriods[2], text: timePeriods[2] },
    { key: 'year', label: timePeriods[3], text: timePeriods[3] },
  ];
};

// 动态生成 MONTHS_MAP，使用一个占位数组
const PLACEHOLDER_MONTHS = Array.from({ length: 12 }, (_, i) => i + 1);
const MONTHS_MAP = YEARS.reduce((acc, year) => {
  acc[year] = PLACEHOLDER_MONTHS;
  return acc;
}, {});

const MonthList = ({ year, monthsMap, selectedMonthItem, setSelectedMonthItem, setSelectedYear, setSelectedMonth }) => {
  const { t } = useTranslation();
  const currentDate = new Date();
  const currentYear = currentDate.getFullYear();
  const currentMonthIndex = currentDate.getMonth();

  // 过滤月份列表
  const filteredMonths = year === currentYear 
    ? monthsMap[year].slice(0, currentMonthIndex + 1) 
    : monthsMap[year];

  return (
    <ul>
      {filteredMonths.map((_, index) => {
        const monthKey = `${year}-${String(index + 1).padStart(2, '0')}`;
        const translatedMonth = t('products.months', { returnObjects: true })[index]; // 获取翻译后的月份
        return (
          <li
            key={index}
            className={selectedMonthItem === monthKey ? 'active' : ''}
            onClick={() => {
              setSelectedMonthItem(monthKey);
              setSelectedYear(year);
              setSelectedMonth(String(index + 1).padStart(2, '0'));
            }}
          >
            {translatedMonth}
          </li>
        );
      })}
    </ul>
  );
};

const Products = () => {
  const currentYear = new Date().getFullYear();
  // 过滤掉大于当前年份的年份
  const filteredYears = YEARS.filter(year => year <= currentYear);

  // 使用过滤后的年份和本地定义的月份映射
  const years = filteredYears;
  const monthsMap = MONTHS_MAP;
  
  const [dateState, setDateState] = useState({
    selectedYear: new Date().getFullYear(),
    selectedMonth: String(new Date().getMonth() + 1).padStart(2, '0'),
    selectedDate: '',
    currentMonth: '',
    monthDays: []
  });

  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [navMode, setNavMode] = useState('day');
  const [search, setSearch] = useState('');
  const dateTabsRef = useRef(null);
  const [scrollPos, setScrollPos] = useState(0);
  // 默认展开 2025 的子节点
  const [expandedYears, setExpandedYears] = useState({ 2025: true }); 

  // 获取翻译文案
  const { timePeriods, bestOf } = useTimePeriodTranslations();
  const NAV_MODES = generateNavModes(timePeriods);

  // 定义 fetchProducts 函数
  const fetchProducts = async (year, month, day) => {
    const url = API_URL_TEMPLATE.replace('${year}', year).replace('${month}', month).replace('${day}', day);
    console.log('发起的 API 请求地址:', url); // 打印请求地址
    try {
      setLoading(true); // 开始请求时设置为加载中
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const data = await response.json();
      console.log('API 返回数据:', data); // 打印返回数据
      if (data.code === 0) {
        console.log('code ===0 '); 
        setProducts(data.data);
        // 打印封装到 products 里的数据
        console.log('封装到 products 里的数据:', data.data); 
      } else {
        setProducts([]);
        alert(NO_DATA_MESSAGE);
      }
    } catch (error) {
      console.error('Error fetching products:', error);
    } finally {
      setLoading(false); // 请求结束，无论成功或失败都设置为加载完成
    }
  };

  const toggleYear = (year) => {
    setExpandedYears(prevState => ({
      ...prevState,
      [year]: !prevState[year]
    }));
  };

  const generateMonthDays = (year, month) => {
    const date = new Date(year, month, 0);
    const totalDays = date.getDate();
    return Array.from({length: totalDays}, (_, i) => 
      String(i + 1).padStart(2, '0')
    );
  };

  // 初始化日期状态
  useEffect(() => {
    if (navMode === 'day') {
      const now = new Date();
      const yesterday = new Date(now);
      yesterday.setDate(now.getDate() - 1);
      const year = yesterday.getFullYear();
      const month = String(yesterday.getMonth() + 1).padStart(2, '0');
      const day = String(yesterday.getDate()).padStart(2, '0');
      
      const newDateState = {
        selectedYear: year,
        selectedMonth: month,
        currentMonth: `${year}-${month}`,
        monthDays: generateMonthDays(year, parseInt(month)),
        selectedDate: `${year}-${month}-${day}`
      };
      
      setDateState(prev => ({
        ...prev,
        ...newDateState
      }));
    }
  }, [navMode]);

  // 处理月份变化
  useEffect(() => {
    if (navMode === 'day') {
      const { selectedYear, selectedMonth } = dateState;
      setDateState(prev => ({
        ...prev,
        currentMonth: `${selectedYear}-${selectedMonth}`,
        monthDays: generateMonthDays(selectedYear, parseInt(selectedMonth)),
      }));
    }
  }, [navMode, dateState.selectedYear, dateState.selectedMonth]);

  // 发起 API 请求
  useEffect(() => {
    if (navMode === 'day' && dateState.selectedDate) {
      const [year, month, day] = dateState.selectedDate.split('-');
      fetchProducts(year, month, day);
    }
  }, [navMode, dateState.selectedDate]);

  const [selectedMonthItem, setSelectedMonthItem] = useState(() => {
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const year = yesterday.getFullYear();
    const month = String(yesterday.getMonth() + 1).padStart(2, '0');
    return `${year}-${month}`;
  });

  return (
    <div className="products-layout">
      {/* 添加左侧导航栏 */}
      <div className="left-nav">
        {years.map(year => ( // 使用过滤后的 years 数组
          <div key={year}>
            <button onClick={() => toggleYear(year)}>
              {year}
            </button>
            {expandedYears[year] && (
              <MonthList
                year={year}
                monthsMap={monthsMap}
                selectedMonthItem={selectedMonthItem}
                setSelectedMonthItem={setSelectedMonthItem}
                setSelectedYear={(newYear) => setDateState(prev => ({ ...prev, selectedYear: newYear }))}
                setSelectedMonth={(newMonth) => setDateState(prev => ({ ...prev, selectedMonth: newMonth }))}
              />
            )}
          </div>
        ))}
      </div>
      <div className="products-main">
        <div className="sub-nav-row">
          <div className="nav-title-and-search">
            <div className="search-bar">
              <input 
                type="text" 
                placeholder="Search products..." 
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
            </div>
            <div className="nav-title-and-tabs">
              <div className="best-of-title">
                {/* 修改为使用变量 bestOf */}
                {bestOf} {NAV_MODES.find(m => m.key === navMode)?.text}
              </div>
            </div>
          </div>
          <div className="sub-nav">
            {NAV_MODES.map(mode => (
              <button
                key={mode.key}
                className={`sub-nav-btn ${navMode === mode.key ? 'active' : ''}`}
                onClick={() => setNavMode(mode.key)}
              >
                {mode.label}
              </button>
            ))}
          </div>
        </div>
        
        {/* 添加日期数字显示区域 */}
        {navMode === 'day' && dateState.monthDays.length > 0 && (
          <div className="date-tabs-row">
            <div className="date-tabs">
              {dateState.monthDays.map(day => (
                <button
                  key={day}
                  className={`date-tab ${dateState.selectedDate === `${dateState.selectedYear}-${dateState.selectedMonth}-${day}` ? 'active' : ''}`}
                  onClick={() => {
                    const newDate = `${dateState.selectedYear}-${dateState.selectedMonth}-${day}`;
                    setDateState(prev => ({ 
                      ...prev, 
                      selectedDate: newDate
                    }));
                  }}
                >
                  {day}
                </button>
              ))}
            </div>
          </div>
        )}
        
        <div className="products-container">
          {loading ? (
            <p>加载中...</p>
          ) : (
            // 检查 products 是否为数组且长度大于 0
            !Array.isArray(products) || products.length === 0 ? (
              <p>暂无产品数据。</p>
            ) : (
              <div className="products-grid">
                {products.map(product => (
                  <div key={product.id} className="product-card">
                    <div className="product-header">
                      <div className="product-rank">{product.product_rank}</div>
                      <img
                        src={product.product_name_logo_src}
                        alt={product.product_name}
                        className="product-logo"
                      />
                      <div className="product-info">
                        <h3>
                          <a href={product.product_url} target="_blank" rel="noopener noreferrer">
                            {product.product_name}
                          </a>
                        </h3>
                        <p className="description-en">{product.product_desc}</p>
                        <p className="description-cn">{product.product_cn_desc}</p>
                        {/* 将 product-tags 和 product-stats 移动到这里 */}
                        <div className="product-meta">
                          <div className="product-tags">
                            {product.product_tag1 && <span className="tag">{product.product_tag1}</span>}
                            {product.product_tag2 && <span className="tag">{product.product_tag2}</span>}
                            {product.product_tag3 && <span className="tag">{product.product_tag3}</span>}
                          </div>
                          <div className="product-stats">
                            <span className="upvotes">👍 {product.product_upvote_count}</span>
                            <span>💬 {product.product_chat_count}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )
          )}
        </div>
      </div>
    </div>
  );
};

export default Products;

